﻿using HBase;
using HBase.cache;
using hCommand.entity;
using hCommand.mySql;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics.Contracts;
using System.Net;
using System.Net.NetworkInformation;

namespace hCommand {
    public class TaskBackTask : ZtTask {

        public TaskBackTask() {
            time = 100;
        }

     

        public IMServer mServer = GuidangFactray.getDal<IMServer>();
        IChouYangServer chouyangServer = WMSDalFactray.getDal<IChouYangServer>();
     


        public override bool excute() {
            DateTime begin = chouyangServer.getLastEqupEndTime();
            var n = new DateTime(DateTime.Now.Ticks / (HUtil.ticksSecRate * 3600L) * HUtil.ticksSecRate * 3600L);
            if (n.Ticks - begin.Ticks < HUtil.ticksSecRate * 3600L) {
                return true;
            }
            Dictionary<String, List<EqupPos>> data = loadData(begin, n);
        

            foreach (var v in data) {
                CyEqup e = MyCache.getValue<CyEqup>("CyEqup", v.Key);
                createEqupUse(e, v.Value);
            }

            chouyangServer.runProcedure(BaseConfig.BaseDBConnStr, "use_sync", new SqlParameter("user_id", 0));
            chouyangServer.setLastEqupEndTime(0, n);
            return true;
        }

        Dictionary<String, List<EqupPos>> loadData(DateTime begin ,DateTime end) {
            Dictionary<String, List<EqupPos>> data = new Dictionary<string, List<EqupPos>>();
            List<String> names = CyUtil.getNames(begin, end);

           
            for ( int i=0;i< names.Count;i++) {
                String name = names[i];
                chouyangServer.runProcedure("main", "create_equp_use", new SqlParameter("myname", name.Substring(1,6)));
             
                statOneDay(name, begin, end, data);
            }
            return data;
            
        }
        void statOneDay( String name , DateTime begin, DateTime end, Dictionary<String, List<EqupPos>> data)
        {
         
            BsonDocument query = new BsonDocument();
            query["time"] = new BsonDocument();
            query["time"]["$gte"] = begin;
            query["time"]["$lt"] = end;
            BsonDocument sort = new BsonDocument();
            sort["time"] = 1;
          
            List<BsonDocument> list = mServer.queryAll("main", name, query, sort);
            foreach (BsonDocument log in list)
            {
                EqupPos t = BsonSerializer.Deserialize<EqupPos>(log);
                t.time = t.time.AddHours(8);
           
                if (!data.ContainsKey(t.code)) {
                    data.Add(t.code, new List<EqupPos>());
                }
                data[t.code].Add(t);
              
            }

        }


     


       
        void createEqupUse(CyEqup e, List<EqupPos> posALl) {
            
    
           
         
            posALl.Sort(); 
            EqupUse use = new EqupUse();
            for (int i = 0; i < posALl.Count; i++) {
                EqupPos pos = posALl[i];

                if (use.begin.Ticks == 0) {
                    setBegin(use, pos, e);
                } else {

                    if (use.begin.Hour != pos.time.Hour) {
                        use.end = posALl[i - 1].time;
                        try {
                            chouyangServer.insert(BaseConfig.BaseDBConnStr, "Equp_Use" + use.begin.ToString("yyyyMM"), use); 
                       } catch (Exception e1){

                            LoggerCommon.errorFile("统计异常", e1);
                        }

                        use = new EqupUse();
                        setBegin(use, pos, e);
                    }
                }
                use.t += pos.i > 0 ? 1 : 0;
                use.w += pos.w > 0 ? 1 : 0;
                use.e += pos.e > 0 ? 1 : 0;
                use.tmp = use.tmp > pos.tmp ? use.tmp : pos.tmp;
            }

            
            use.end = posALl[posALl.Count - 1].time;
            try
            {
                chouyangServer.insert(BaseConfig.BaseDBConnStr, "Equp_Use" + use.begin.ToString("yyyyMM"), use);

            }
            catch (Exception e1)
            {

                LoggerCommon.errorFile("统计异常", e1);
            }



        }

        void setBegin(EqupUse use, EqupPos pos, CyEqup e) {

            use.begin = pos.time;
            use.id = HUtil.toLong(pos._id);
            use.userId = e.userId;
            use.equpId = e.id;
            use.status = 1;
        }
    }
}
